package com.hmdp.utils;

import org.springframework.data.redis.core.*;
import org.springframework.stereotype.*;

import java.time.*;
import java.time.format.*;
import java.util.concurrent.*;

@Component
public class RedisIdWorker {
    /**
     * 开始时间戳
     */
    private static final long BEGIN_TIMESTAMP = 1712105675L;
    /**
     * 序列号的位数
     */
    private static final int COUNT_BITS = 32;

    private StringRedisTemplate stringRedisTemplate;

    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public long nextId(String keyPrefix) {
        // 1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIMESTAMP;

        // 2.生成序列号
        // 2.1.获取当前日期，精确到天
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        // 2.2.自增长
        String countKey = "icr:" + keyPrefix + ":" + date;
        long count = stringRedisTemplate.opsForValue().increment(countKey);
        //设置过期时间
        if (count == 1) {
            // 获取当天的 00:00
            LocalDateTime todayStart = LocalDateTime.now().with(LocalTime.MIN);
            // 计算当前时间到今天结束的秒数
            long secondsUntilMidnight = Duration.between(LocalDateTime.now(), todayStart.plusDays(1)).getSeconds();
            // 设置过期时间为当天剩余时间
            stringRedisTemplate.expire(countKey, secondsUntilMidnight, TimeUnit.SECONDS);
        }
        // 3.拼接并返回
        return timestamp << COUNT_BITS | count;
    }
}